#!/bin/bash
JAR_NAME="$2.jar"
ACTIVE=$3

#使用说明：sh deploy.sh restart
usage(){
  echo "usage: sh deploy.sh [start|restart|stop|status]"
  echo "  start    : start the application"
  echo "  restart  : restart the application"
  echo "  stop     : stop the application"
  echo "  status   : check the status of the application"
  exit 1
}

#检查程序是否在运行
is_exist() {
  pid=$(pgrep -f "$JAR_NAME")
  # 如果找到匹配，则为0，否则为1
  return $?
}
#启动
start(){
  is_exist
  if [ $? -eq "0" ]; then
    echo ">>> ${JAR_NAME} is already running pid=${pid} <<<"
  else
    nohup java -Xms256m -Xmx256m -jar $JAR_NAME --spring.profiles.active=${ACTIVE} > /dev/null 2>&1 &
    echo ">>> ${JAR_NAME} is running <<<"
   fi
}

#重启
restart(){
  stop
  wait $!  # 等待 stop 函数中的进程完全退出
  start
}

# 停止
stop() {
  is_exist
  if [ $? -eq "0" ]; then
    echo ">>> ${JAR_NAME} is stopping pid=${pid} <<<"
    kill -15 $pid  # 发送终止信号
    sleep 1  # 等待一段时间
    is_exist
    if [ $? -eq "0" ]; then
      # 如果进程仍然存在，则使用 kill -9 强制终止
      echo ">>> ${JAR_NAME} did not stop gracefully, force killing <<<"
      kill -9 $pid
    fi
  else
    echo ">>> ${JAR_NAME} is not running <<<"
  fi
}

#状态
status(){
  is_exist
  if [ $? -eq "0" ]; then
    echo ">>> ${JAR_NAME} is running pid is ${pid} <<<"
  else
    echo ">>> ${JAR_NAME} is not running <<<"
  fi
}

case "$1" in
  "start")
    start
    ;;
  "restart")
    restart
    ;;
  "stop")
    stop
    ;;
  "status")
    status
    ;;
  *)
    usage
    ;;
esac
exit 0